<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="类型名称" prop="typeName">
                <el-input v-model="queryParams.typeName" placeholder="请输入类型名称" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item label="扩展名" prop="extension">
                <el-input v-model="queryParams.extension" placeholder="请输入扩展名" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                <el-button icon="refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="success" plain icon="edit" :disabled="single" @click="handleUpdate"
                    v-hasFunc="'filetypes:edit'">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="delete" :disabled="multiple" @click="handleDelete"
                    v-hasFunc="'filetypes:del'">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain icon="plus" @click="handleAdd"
                    v-hasFunc="'filetypes:add'">新增</el-button>
            </el-col>
            <right-toolbar :showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" highlight-current-row>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="主类别" align="center" prop="group" :show-overflow-tooltip="true"
                v-if="columns.showColumn('group')">
                <template #default="scope">
                    <dict-tag :options="file_category" :value="scope.row.group" />
                </template>
            </el-table-column>
            <el-table-column label="类型名称" align="center" prop="typeName" :show-overflow-tooltip="true"
                v-if="columns.showColumn('typeName')">
                <template #default="scope">
                    {{ scope.row.typeName }}
                </template>
            </el-table-column>
            <el-table-column label="扩展名" align="center" prop="extension" :show-overflow-tooltip="true"
                v-if="columns.showColumn('extension')">
                <template #default="{ row }">
                    <el-space>
                        <el-tag type="primary" v-for="item in row.extension">{{ item }}</el-tag>
                    </el-space>
                </template>
            </el-table-column>
            <el-table-column label="MIME类型" align="center" prop="mimeType" :show-overflow-tooltip="true"
                v-if="columns.showColumn('mimeType')">
                <template #default="scope">
                    {{ scope.row.mimeType }}
                </template>
            </el-table-column>
            <el-table-column label="是否允许" align="center" prop="isActive" :show-overflow-tooltip="true"
                v-if="columns.showColumn('isActive')">
                <template #default="scope">
                    <dict-tag :options="sys_normal_disable" :value="scope.row.isActive" />
                </template>
            </el-table-column>
            <el-table-column label="图标" align="center" prop="icon" :show-overflow-tooltip="true"
                v-if="columns.showColumn('icon')">
                <template #default="scope">
                    <IconPlus v-if="scope.row.icon" :name="scope.row.icon" style="display: unset;"></IconPlus>
                </template>
            </el-table-column>
            <el-table-column label="排序" align="center" prop="order" :show-overflow-tooltip="true"
                v-if="columns.showColumn('order')">
                <template #default="scope">
                    {{ scope.row.order }}
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createdAt" :show-overflow-tooltip="true"
                v-if="columns.showColumn('createdAt')">
                <template #default="scope">
                    {{ parseTime(scope.row.createdAt) }}
                </template>
            </el-table-column>


            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button v-hasFunc="'filetypes:edit'" type="primary" text icon="edit"
                        @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button v-hasFunc="'filetypes:del'" type="primary" text icon="delete"
                        @click="handleDelete(scope.row)">删除</el-button>
                    <el-button v-hasFunc="'filetypes:info'" type="primary" text icon="view"
                        @click="handleView(scope.row)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body draggable align-center
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-row :gutter="20">
                    <el-col :lg="24">
                        <el-form-item label="主类别" prop="typeName">
                            <el-select v-model="form.group" placeholder="请选择主类别" clearable>
                                <el-option v-for="dict in file_category" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="类型名称" prop="typeName">
                            <el-input v-model="form.typeName" placeholder="请输入类型名称" clearable />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="24">
                        <el-form-item label="MIME类型" prop="mimeType">
                            <el-input v-model="form.mimeType" placeholder="请输入MIME类型" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="类型图标" prop="icon">
                            <el-popover placement="bottom-start" :width="540" trigger="click">
                                <template #reference>
                                    <el-input v-model="form.icon" placeholder="点击选择图标" @blur="showSelectIcon" readonly>
                                        <template #prefix>
                                            <IconPlus v-if="form.icon" :name="form.icon" />
                                        </template>
                                        <template #suffix>
                                            <el-icon>
                                                <search />
                                            </el-icon>
                                        </template>
                                    </el-input>
                                </template>
                                <icon-select ref="iconSelectRef" @selected="handleSelectIcon"
                                    :active-icon="form.icon" />
                            </el-popover>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="是否允许" prop="isActive">
                            <el-radio-group v-model="form.isActive">
                                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value"> {{
                                    dict.label }}</el-radio>
                            </el-radio-group>
                            <!-- <el-select v-model="form.isActive" placeholder="请选择是否允许" clearable>
                                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select> -->
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="排序" prop="order">
                            <el-input-number v-model="form.order" placeholder="请输入排序" controls-position="right" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="常见扩展名" prop="extension">
                            <div style="display: flex;gap: 10px;align-items:center">
                                <el-tag v-for="tag in form.extension" :key="tag" closable :disable-transitions="false"
                                    @close="handleTagClose(tag)">
                                    {{ tag }}
                                </el-tag>
                                <el-input v-if="inputVisible" ref="inputTagRef" v-model="inputTagValue" class="w-20"
                                    @keyup.enter="handleAppendTag" @blur="handleAppendTag" style="width: 50px;" />
                                <el-button v-else plain icon="plus" @click="showTagInput">添加</el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="描述" prop="order">
                            <el-input v-model="form.description" placeholder="请输入详情描述" type="textarea" resize="none"
                                show-word-limit maxlength="100" :rows="6" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="submitForm" v-if="operateType == 0 || operateType == 1">确
                    定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
// import SvgIcon from "@/components/SvgIcon";
import IconSelect from "@/components/IconSelect";

import { ref, reactive, onMounted } from "vue";
import { listFileTypes, getFileTypes, delFileTypes, addFileTypes, updateFileTypes } from "@/api/system/filetypes.js";


const { proxy } = getCurrentInstance()

//字典数据
const dicts = ["sys_normal_disable", "file_category"];
const dictRefs = proxy.useDict(...dicts);
const { sys_normal_disable, file_category } = dictRefs;

//弹窗操作类型
//0:新增，1：修改，2:查看
const operateType = ref(0)
//表单ref
const formRef = ref();
// 遮罩层
const loading = ref(true);
// 选中数组
const selected = ref([]);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 数据集
const dataList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);

const iconSelectRef = ref();

const inputTagValue = ref();
const inputVisible = ref(false);
const inputTagRef = ref();
//默认时间范围
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])



// 查询参数
const queryParams = reactive({
    pageIndex: 1,
    pageSize: 10,
    typeName: undefined,
    extension: undefined,
});



const state = reactive({
    single: true,
    multiple: true,
    form: {
        isActive: true,
        extension: []
    },
    rules: {
        //customerId: [{ required: true, message: "客户id不能为空", trigger: "blur"    , type: "number"  }],
        //name: [{ required: true, message: "商品名称不能为空", trigger: "blur"     }],
    },
    options: {
        // 商品种类 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
        typeOptions: [],
    }
})

const { form, rules, options, single, multiple } = toRefs(state)


//所有列
const columns = ref([
    { visible: true, prop: 'group', label: '主类别' },
    { visible: true, prop: 'typeName', label: '类型名称' },
    { visible: true, prop: 'extension', label: '扩展名' },
    { visible: true, prop: 'mimeType', label: 'MIME类型' },
    { visible: true, prop: 'isActive', label: '是否允许' },
    { visible: true, prop: 'icon', label: '图标' },
    { visible: false, prop: 'order', label: '排序' },
    { visible: true, prop: 'createdAt', label: '创建时间' },
]);

/** 展示下拉图标 */
const showSelectIcon = () => {
    iconSelectRef.value.reset();
}

/** 选择图标 */
const handleSelectIcon = (name) => {
    form.value.icon = name;
}

// 获取列表方法
const getList = () => {
    loading.value = true;
    listFileTypes(queryParams).then((response) => {
        dataList.value = response.result;
        total.value = response.totalNum;
        loading.value = false;
    });
};

// 重置表单
const reset = () => {
    form.value = {
        isActive: true,
        order: 999
    };
};

// 搜索按钮操作
const handleQuery = () => {
    queryParams.pageIndex = 1;
    getList();
};

// 重置按钮操作
const resetQuery = () => {
    reset();
    handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
    selected.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
    reset();
    operateType.value = 0;
    open.value = true;
    title.value = "添加数据";
};

// 修改按钮操作
const handleUpdate = (row) => {
    reset();
    operateType.value = 1;
    const key = row.id || selected.value;
    getFileTypes(key).then((response) => {
        Object.assign(form.value, response);
        open.value = true;
        title.value = "修改数据";
    });
};


//查看
const handleView = (row) => {
    reset();
    operateType.value = 2;
    var key = row.id;
    getFileTypes(key).then((response) => {
        Object.assign(form.value, response);
        open.value = true;
        title.value = "查看明细";
    });
}

// 提交按钮
const submitForm = () => {
    const validateForm = formRef.value?.validate;
    if (validateForm) {
        validateForm((valid) => {
            if (valid) {
                const apiCall = form.value.id ? updateFileTypes : addFileTypes;
                apiCall(form.value).then(() => {
                    proxy.$modal.msgSuccess("操作成功");
                    open.value = false;
                    getList();
                });
            }
        });
    }
};

//取消弹窗
const cancel = () => {
    open.value = false;
    proxy.resetForm("form")
}

// 删除按钮操作
const handleDelete = (row) => {
    const keys = [].concat(row.id || selected.value);
    proxy.$modal.confirm("是否确认删除编号为" + keys + "的数据项？")
        .then(() => delFileTypes(keys))
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
};

//移除常用扩展名
const handleTagClose = (tag) => {
    let dynamicTags = form.value.extension || [];
    dynamicTags.splice(dynamicTags.indexOf(tag), 1)
    form.value.extension = dynamicTags;
}

//追加常用扩展名
const handleAppendTag = () => {
    let dynamicTags = form.value.extension || [];
    if (inputTagValue.value) {
        dynamicTags.push(inputTagValue.value)
    }
    inputVisible.value = false
    inputTagValue.value = ''
    form.value.extension = dynamicTags
}

const showTagInput = () => {
    inputVisible.value = true
    nextTick(() => {
        inputTagRef.value?.focus()
    })
}

// 导出按钮操作
const handleExport = () => {
    download("system//export", queryParams, `menu_${new Date().getTime()}.xlsx`);
};

// 页面加载时调用获取列表方法
onMounted(getList);
</script>
